package msu.ml.core.xml;

import msu.ml.core.*;
import msu.ml.data.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.util.*;

/**
 * @author Reginald M Mead
 * @version 1.0
 */
public class ValidationPostProcessorParser implements IPostProcessorParser
{
	private HashMap<String, IClassificationRuleParser> ruleParsers;

	public ValidationPostProcessorParser()
	{
		ruleParsers = new HashMap<String, IClassificationRuleParser>();
	}

	public void addClassificationRuleParser(String key, 
			IClassificationRuleParser parser)
	{
		ruleParsers.put(key, parser);
	}


   public IDataPostProcessor parse(Element element)
   {
      try
      {
         int classes = Integer.parseInt(element.getAttribute("classes"));

         if(ApplicationSettings.getInstance().getConfig("verbose").equals("true"))
            System.out.println("Validation Post Processor, " + classes + " classes");

         Element sweepElement = (Element)(element.getElementsByTagName(
                  "sweep_rule").item(0));
         Element pulseElement = (Element)(element.getElementsByTagName(
                  "pulse_rule").item(0));

         ValidationPostProcessor processor = new ValidationPostProcessor();
         processor.setExperimentDocument(element.getOwnerDocument());
         processor.setOutput(element.getAttribute("output"));
         processor.setTransformation(element.getAttribute("transformation"));
         

         if(ApplicationSettings.getInstance().getConfig("verbose").equals("true"))
            System.out.print("\t Sweep Rule: ");
         processor.setSweepClassificationRule(
               parseClassificationRule(sweepElement));
         if(ApplicationSettings.getInstance().getConfig("verbose").equals("true"))
            System.out.print("\t Pulse Rule: ");
         processor.setPulseClassificationRule(
               parseClassificationRule(pulseElement));
         processor.setNumClasses(classes);

         return processor;
      }
      catch(Exception e)
      {
         System.out.println(e.getStackTrace());
         return null;
      }
   }

   private ClassificationRule parseClassificationRule(Element element)
   {
      NodeList nodes = element.getChildNodes(); 
      for(int i = 0; i < nodes.getLength(); i++)
      {
         Node node = nodes.item(i);
         if(ruleParsers.containsKey(node.getNodeName()))
         {
				return ruleParsers.get(node.getNodeName()).parse((Element)node);
			}
		}
      return null;
	}
}
